/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

/**
 *
 * @author Kilian Ito
 */
public class ListWord {
    public final static String WordFolder = ".." + File.separator + "Words";
    private String w = "";
    private String pathw = "";
    private String infoVersion = "";
    private int version = -1;
    private int lastVersion = -1;
    private String text = "";
    public ListWord()
    {
        // pas obligatoire
        File f = new File(WordFolder);
        if (!f.exists())
            f.mkdir();
    }

    // Mot traite
    public void setWord(String word)
    {
        w = "" + word;
        setConvertedWord(w);
    }
    public String getWord()
    {
        return w;
    }



    // Le mot existe
    public void setExist(String b)
    {
        
    }
    public String getExist()
    {
        File folder = new File(WordFolder + File.separator + getConvertedWord());
        if (!(folder.exists() && folder.isDirectory()))
            return "false";

        File html = new File(WordFolder + File.separator + getConvertedWord() + File.separator + "index.html");
        return html.exists()?"true":"false";
    }



    // Selectionne la version a editer
    public void setSelectVersion(String i)
    {
        int v = getInt(i);
        if (v <= getInt(getLastVersion()))
            version = v;
    }
    public String getSelectVersion()
    {
        return String.valueOf(version);
    }

    // derniere version en cours
    public String getLastVersion()
    {
        File folder = new File(WordFolder + File.separator + getConvertedWord());
        if (!folder.exists())
            return "-1";
        return Integer.toString(folder.listFiles(new FileFilter(){
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().matches(".*.txt");
            }
        }).length - 1);
    }
    public void setLastVersion(String i)
    {

    }

    // derniere version actuelle (lors de l'edition)
    public String getMyLastVersion()
    {
        return Integer.toString(lastVersion);
    }
    public void setMyLastVersion(String i)
    {
        
    }

    // mot traité
    public String getHisto(){
        String res = "<ul>";
        ArrayList<File> ll = new ArrayList<File>();
        File folder = new File(WordFolder + File.separator + getConvertedWord());
        if (folder.exists() && folder.isDirectory())
        {
            for (File f :folder.listFiles(new FileFilter(){
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().matches(".*.txt");
                }
            }))
            {
                ll.add(f);
            }
        }
        Collections.sort(ll, new Comparator<File>() {

            public int compare(File o1, File o2) {
                return (int)(o1.lastModified() - o2.lastModified());
            }
        });
        for (File f : ll)
            res += "<li><a href=\"" + w + "!" + f.getName().replaceAll("^([0-9]*)\\..*", "$1") + "\">" + reverseConvertWord(f.getName().replaceAll("^([0-9]*)\\.(.*)\\.txt", "$1 - $2"))+ "</a></li>";
        return res + "</ul>";
    }
    public void setHistos(String customers)
    {

    }

    // mot traité
    public String getWords(){
        ArrayList<String> res = new ArrayList<String>();
        File folder = new File(WordFolder);
        for (File f :folder.listFiles(new FileFilter(){
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        }))
            res.add(reverseConvertWord(f.getName()));
        Collections.sort(res);
        String str = "<ul>";
        for (String s : res)
            str += "<li><a href=\"" + reverseConvertWord(s) + "\">" + reverseConvertWord(s) + "</a></li>";
        return str + "</ul>";
    }
    public void setWords(String customers)
    {

    }

    // text du dernier version
    public String getText()
    {
        lastVersion = getInt(getLastVersion());
        if (version == -1)
            version = lastVersion;
        return readFile(WordFolder + File.separator + getConvertedWord() + File.separator + getFileVersion(version));
    }
    public void setText(String text)
    {
        if (getExist().equals("false"))
        {
            File f = new File(WordFolder + File.separator + getConvertedWord());
            f.mkdir();
        }
        saveVersion(text);
        saveHTML(text);
    }

     // HTML du dernier version
    public String getHtml()
    {
        return readFile(WordFolder + File.separator + getConvertedWord() + File.separator + "index.html");
    }
    public void setHtml(String text)
    {
        
    }

    // convertir le mot en nom pour un r�pertoire
    public String getConvertedWord()
    {
        return pathw;
    }
    public void setConvertedWord(String word)
    {
        pathw=convertFileName(w);
    }

    private String convertFileName(String word)
    {
        String res=""+word;
        res = res.replaceAll(" ", "_");
        res = res.replaceAll("\"", "&quote;");
        res = res.replaceAll("/", "&bsl;");
        res = res.replaceAll("\\", "&sl;");
        res = res.replaceAll("\\*", "&star;");
        res = res.replaceAll("\\?", "&quest;");
        res = res.replaceAll("\\<", "&lg;");
        res = res.replaceAll("\\>", "&rg;");
        res = res.replaceAll("\\|", "&ou;");
        res = res.replaceAll("\\:", "&pp;");
        return res;
    }

    // information sur la version
    public String getVersionInfo()
    {
        return infoVersion;
    }
    public void setVersionInfo(String s)
    {
        infoVersion = "" + s;
    }

    // ecrire dans un fichier
    private void writeFile(String fichier, String text)
    {
        try
        {
            FileWriter fw = new FileWriter(fichier, true);
            BufferedWriter output = new BufferedWriter(fw);
            output.write(text);
            output.flush();
            output.close();
        }
        catch(IOException ioe){
            System.err.print(ioe.getMessage());
        }
    }

    // Lire le contenu d'un fichier
    private String readFile(String fichier)
    {
        String chaine="";

        try{
            InputStream ips=new FileInputStream(fichier);
            InputStreamReader ipsr=new InputStreamReader(ips);
            BufferedReader br=new BufferedReader(ipsr);
            String ligne;
            while ((ligne=br.readLine())!=null)
                    chaine+=ligne + System.getProperty("line.separator");
            br.close();
        }
        catch (Exception e){
                System.err.print(e.getMessage());
        }
        return chaine;
    }

    // convertir le code Wiki en page HTML
    private String convertText(String text)
    {
        String res = "" + text;
        res = res.replaceAll("(http://[^ ]*)", "<a href=\"$1\" target=\"_blank\">$1</a>");
        res = res.replaceAll("\\[(.*)\\]", "<a href=\"$1\">$1</a>");
        res = res.replaceAll("\\+\\+(.*)\\+\\+", "<b>$1</b>");
        res = res.replaceAll("\\+([^\\+]*)\\+", "<i>$1</i>");
        res = res.replaceAll("(?m)^!!!(.*)$", "<h3>$1</h3>");
        res = res.replaceAll("(?m)^!!(.*)$", "<h2>$1</h2>");
        res = res.replaceAll("(?m)^!(.*)$", "<h1>$1</h1>");
        res = res.replaceAll("(?m)^---$", "<hr />");
        res = res.replaceAll("(?m)^([^!].*)$", "$1<br />");
        return res;
    }

    // Enregistrer la page web
    private void saveHTML(String text)
    {
        String path = WordFolder + File.separator + getConvertedWord() + File.separator + "index.html";
        File f = new File(path);
        f.delete();
        writeFile(path, convertText(text));
    }

    // Enregistrer la derniere version
    private void saveVersion(String text)
    {
        writeFile(WordFolder + File.separator + getConvertedWord() + File.separator + (getInt(getLastVersion()) + 1) + "." + convertFileName(infoVersion) + ".txt", text);
        lastVersion = getInt(getLastVersion());
        version = lastVersion;
    }

    // R�cup�rer le mot d'origine
    private String reverseConvertWord(String word)
    {
        String res = "" + word;
        res = res.replaceAll("_", " ");
        res = res.replaceAll("&quote;", "\"");
        res = res.replaceAll("&bsl;", "/");
        res = res.replaceAll("&sl;", "\\");
        res = res.replaceAll("&star;", "*");
        res = res.replaceAll("&quest;", "?");
        res = res.replaceAll("&lg;", "<");
        res = res.replaceAll("&rg;", ">");
        res = res.replaceAll("&ou;", "|");
        res = res.replaceAll("&pp;", ":");
        return res;
    }

    private String getFileVersion(int i)
    {
        final int vers = i;
        File folder = new File(WordFolder + File.separator + getConvertedWord());
        if (folder.exists() && folder.isDirectory())
        {
            for (File f :folder.listFiles(new FileFilter(){
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().matches(vers + "\\..*.txt");
                }
            }))
            {
                return f.getName();
            }
        }
        return "";
    }

    private int getInt(String s)
    {
        if (s == null || s.equals(""))
            return -1;
        else
        {
            try
            {
                return Integer.valueOf(s).intValue();
            }
            catch (Exception e)
            {
                return -1;
            }
        }
    }
    private String setConvertedText(String text)
    {
        return convertText(text);
    }
}
